<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content hp100">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between">
        <div class="flex_start ">
          <div class="table_filter_search">
            <el-input v-model="params.commonSearch" class="pub_input pub_input_search" placeholder="搜索客户名称、地址" clearable @keydown.enter.native="handleSearch" @clear="handleSearch">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
          </div>
          <div class="table_filter_search ml12">
            <el-button type="text" class="public_confirm_btn pub_button" @click="handleSearch"> 搜索 </el-button>
          </div>
        </div>
        <div class="flex_start flex_end">
          <div v-if="roleType != 1">
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="showDilogBtn('addDialogVisible')">
              <img src="@/assets/img/orderManagement/add.png" alt="添加客户" />
              <span class="ml5">添加客户</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonRed" @click="delteDataBtn">
              <img src="@/assets/img/orderManagement/delete.png" alt="批量删除" />
              <span class="ml5">批量删除</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w108 pub_button" @click="downloadFile">
              <img src="@/assets/img/orderManagement/download.png" alt="下载模板" />
              <span class="ml5">下载模板</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-upload ref="upload" class="avatar-uploader" :show-file-list="false" action="#" :on-change="uploadChange" :auto-upload="false">
              <el-button type="text" class="w80 pub_button">
                <img src="@/assets/img/orderManagement/import.png" alt="导入" />
                <span class="ml5">导入</span>
              </el-button>
            </el-upload>
          </div>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" size="mini" :data="tableData" tooltip-effect="dark" border :height="`calc(100% - ${72 * $f}px)`" class="wp100 mt12" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" :width="`${50 * $f}`" />
        <el-table-column label="序号" type="index" :width="`${50 * $f}`" align="center" />
        <el-table-column label="客户名称" show-overflow-tooltip prop="customerName" align="center" :min-width="`${200 * $f}`" />
        <el-table-column label="单位地址" show-overflow-tooltip prop="customerAddress" align="center" :min-width="`${300 * $f}`" />
        <el-table-column label="操作" align="center" :min-width="`${200 * $f}`">
          <template slot-scope="{ row }">
            <el-button class="pub_button public_1EB398_btn" type="text" size="mini" @click="looResearchkGroup(row)">课题组</el-button>
            <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="editBtnClick(row)">编辑</el-button>
            <el-button type="text" class="pub_button public_F16363_btn" size="mini" @click="delBtnClick(row)">删除</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
      <div ref="pubPageinationRef" class="pub_pageination flex_center mt18">
        <el-pagination background layout="total,prev, pager, next" :total="tableData.length" :page-size="tableData.length"> </el-pagination>
      </div>
    </div>
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 添加客户 -->
    <PageDialog :title="addParams.id ? '编辑客户' : '添加客户'" :dialog-visible="addDialogVisible" :width="`${600 * $f}px`" @close="closeDialog" @submit="confirmAdd">
      <el-form ref="ruleForm" :model="addParams" :rules="rules" label-width="5rem" class="pub_form_item">
        <el-form-item label="客户单位" prop="customerName">
          <el-input v-model="addParams.customerName" placeholder="请输入客户单位" class="pub_input" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="customerAddress">
          <el-input v-model="addParams.customerAddress" placeholder="请输入单位地址" class="pub_input" :maxlength="30"></el-input>
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
export default {
  mixins: [tableFun],
  data() {
    return {
      params: { commonSearch: '' },
      addParams: { customerAddress: '', customerName: '' },
      dataListOrg: [],
      // 表单验证规则
      rules: {
        customerName: [
          { required: true, message: '请输入客户单位', trigger: 'blur' },
          { max: 20, message: '客户单位不能超过20个字符', trigger: 'blur' }
        ],
        customerAddress: [
          { required: true, message: '请输入单位地址', trigger: 'blur' },
          { max: 30, message: '单位地址不能超过30个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    roleType() {
      //1:超级管理员 2:普通管理员 3:普通员工
      return this.$store.state?.userInfo?.roleType;
    },
    headers() {
      return {
        Authorization: this.$store.state.token
      };
    },
    uploadFileUrl() {
      return 'orderPlusApi/' + this.$url.uploadBusinessLicence;
    }
  },
  created() {
    this.getDataList();
  },
  methods: {
    downloadFile() {
      const link = document.createElement('a');
      link.href = '/static/files/客户导入模板.xlsx'; // 直接放在 public 根目录下
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 上传文件
    async uploadChange(file) {
      const form = new FormData();
      form.append('file', file.raw);
      let res = await this.$api.postFile(this.$url.uploadCustomerInfo, form);
      if (res) {
        this.$message({ message: '上传成功', type: 'success' });
        this.getDataList();
      } else {
        this.$message.error('上传失败');
      }
    },
    //关闭弹窗
    closeDialog() {
      this.selectedRow = null;
      this.multipleSelection = [];
      this.deleteDialogVisible = false;
      this.exporttDialogVisible = false;
      this.orderDialogVisible = false;
      this.importDialogVisible = false;
      this.addDialogVisible = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
    },
    //跳转到查看课题组
    looResearchkGroup(row) {
      this.$router.push({
        path: '/layout/researchGroup',
        query: {
          activeIndex: '4-4',
          customerId: row.id
        }
      });
    },
    async getDataList() {
      let res = await this.$api.get(this.$url.customerAll, this.params);
      this.tableData = res.data;
      this.dataListOrg = res.data;
      if (this.params.commonSearch) {
        this.handleSearch();
      }
    },
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.customerDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.customerDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    handleSearch() {
      this.tableData = this.dataListOrg.filter(item => item.customerName.indexOf(this.params.commonSearch) !== -1 || item.customerAddress.indexOf(this.params.commonSearch) !== -1);
    },
    async confirmAdd() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { id } = this.addParams;
          let url = id ? this.$url.customerUpdate : this.$url.customerAdd;
          let res = await this.$api.post(url, this.addParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.table_content {
  height: calc(100% - 49px);
}
</style>
